package com.thread.example.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:
 * @Description:
 * corePoolSize： 线程池维护线程的最少数量
 * maximumPoolSize：线程池维护线程的最大数量
 * keepAliveTime： 线程池维护线程所允许的空闲时间
 * unit： 线程池维护线程所允许的空闲时间的单位
 * workQueue： 线程池所使用的缓冲队列
 * handler： 线程池对拒绝任务的处理策略
 * @Date: 2019/11/1 14:56
 */
public class DemoController {

    public static void main(String[] args) {
        a();
        b();
    }

    public static void a() {
        long l = System.currentTimeMillis();
        try {
            List<String> resultList = new ArrayList<>();
            ExecutorService executorService = new ThreadPoolExecutor(
                    5,
                    20,
                    1l,
                    TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue<Runnable>(3200),
                    new ThreadPoolExecutor.AbortPolicy());
            for (int i = 0; i < 100; i++) {
                executorService.execute(new Thread(new Worker(resultList, i)));
            }
            executorService.shutdown();
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
            System.out.println(resultList);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        long l2 = System.currentTimeMillis();
        System.out.println("a总耗时：" + (l2 - l));
    }

    public static void b() {
        long l = System.currentTimeMillis();
        try {
            List<String> resultList = new ArrayList<>();
            for (int i = 0; i < 100; i++) {
                Thread.sleep(1000);
                resultList.add(Thread.currentThread().getName());
                System.out.println(Thread.currentThread().getName() + "    is running ----  " + i);
            }
            System.out.println(resultList);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        long l2 = System.currentTimeMillis();
        System.out.println("b总耗时：" + (l2 - l));
    }

    private static class Worker implements Runnable {

        private List<String> resultList;
        private int index;

        public Worker(List<String> resultList, int i) {
            this.index = i;
            this.resultList = resultList;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            resultList.add(Thread.currentThread().getName());
            System.out.println(Thread.currentThread().getName() + "    is running ----  " + index);
        }
    }

}
